﻿var addNewWorkspace;
var fillEnvironmentDdl;
var showDetailNoNav;
var intrnl = false;

workspace = {
    
};

columnNames = ["", "ID", "ClientID", "Environment", "Client", "Client ID", "Created", "Created by", "Last Modified", "Las Modify by", "Status", "Note"];
columnModel =
[
    { "name": "Edit", "index": "Edit", "width": 20, "height": 20, "align": "left", "hidedlg": true, "fixed": true, "search": false, "classes": "editrow", "title": true, "hidden": false, "widthOrg": 20, "resizable": true, "sortable": true, "stype": "text" },
    { "name": "pkUser_ID", "index": "pkUser_ID", "width": 1, "editable": false, "hidedlg": true, "hidden": true, "title": true, "widthOrg": 1, "resizable": true, "sortable": true, "search": true, "stype": "text" },
    { "name": "fkClient_ID", "index": "fkClient_ID", "width": 1, "editable": false, "hidedlg": true, "hidden": true, "title": true, "widthOrg": 1, "resizable": true, "sortable": true, "search": true, "stype": "text" },
    { "name": "Environment.Name", "index": "DisplayName", "width": 80, "editable": false, "hidden": false, "title": true, "widthOrg": 80, "resizable": true, "sortable": true, "search": true, "stype": "text" },
    { "name": "ClientName", "index": "FirstName", "width": 80, "editable": false, "hidden": false, "title": true, "widthOrg": 80, "resizable": true, "sortable": true, "search": true, "stype": "text" },
    { "name": "ClientId", "index": "LastName", "width": 80, "editable": false, "hidden": false, "title": true, "widthOrg": 80, "resizable": true, "sortable": true, "search": true, "stype": "text" },
    { "name": "CreatedOn", "index": "UserEmail", "width": 100, "editable": false, "hidden": false, "title": true, "widthOrg": 100, "resizable": true, "sortable": true, "search": true, "stype": "text" },
    { "name": "CreatedBy", "index": "Role", "width": 60, "align": "left", "editable": false, "hidden": false, "title": true, "widthOrg": 60, "resizable": true, "sortable": true, "search": true, "stype": "text" },
    { "name": "LastModifiedOn", "index": "Title", "width": 80, "align": "center", "editable": false, "title": true, "hidden": false, "widthOrg": 80, "resizable": true, "sortable": true, "search": true, "stype": "text" },
    { "name": "LastModifiedBy", "index": "Phone1", "width": 40, "align": "center", "editable": false, "hidden": true, "searchoptions": {}, "title": true, "widthOrg": 40, "resizable": true, "sortable": true, "search": true, "stype": "text" },
    { "name": "Phone2", "index": "Phone2", "width": 60, "align": "center", "editable": false, "hidden": true, "searchoptions": {}, "title": true, "widthOrg": 60, "resizable": true, "sortable": true, "search": true, "stype": "text" },
    { "name": "Note", "index": "Address1", "width": 80, "align": "left", "editable": false, "hidden": true, "searchoptions": {}, "title": true, "widthOrg": 80, "resizable": true, "sortable": true, "search": true, "stype": "text" }
];

$(document).ready(function() {
    $('.form_txt').keydown(function() {
        promptSave();
    });
    
    $('.form_txtarea').keydown(function() {
        promptSave();
    });
    $('.form_select').change(function() {
        promptSave();
    });

    $('.form_txtarea3').keydown(function() {
        promptSave();
    });
    $('.form_select').change(function() {
        promptSave();
    });

    $(".form_table input:checkbox").click(function() {
        promptSave();
    });

    PageFilter();
});



addNewWorkspace = function() {
    intrnl = true;

    fillEnvironmentDdl('');
    showDetailNoNav();

    $('.detailadd').show();
    $('.detailsave').hide();
    $('.detailactivate').hide();
};


fillEnvironmentDdl = function(curval) {
    $('#work_cboEnvironment').html('');
    var urhtml = '';
    var response = FillDropdown("Environment");
    //var roles = response;
    $.each(response, function(item) {
        urhtml += "<option value='" + response[item] + "' "
        if (curval == response[item]) {
            urhtml += "selected"
        }
        urhtml += " >" + response[item] + "</option>";
    });
    $('#work_cboEnvironment').html(urhtml);
};


showDetailNoNav = function() {
    $('#panel_grid_main').hide();
    $('#panel_grid_sub').show();
    $('#panel_tabs').show();
    //        canvasheight = $('#site_top_middle').height();
    //        loader.css({ height: canvasheight - 182, width: canvaswidth });
    preSave(intrnl);
    try {
        var containerwidth = $('#second_grid_container').width();
        $('#second_list').jqGrid('setGridWidth', containerwidth - 2);
    } catch(err) {

    }
};

promptSave = function() {
    //$('').attr('disabled', true);
    $('.detailadd').button("option", "disabled", false);
    $('.detailsave').button("option", "disabled", false);
    $('.detailcancel').button("option", "label", "Cancel");
};

preSave = function() {
    $('.detailadd').button("option", "disabled", true);
    $('.detailsave').button("option", "disabled", true);
    if (intrnl) {
        $('.detailcancel').button("option", "label", "Back to Workspaces");
    } else {
        $('.detailcancel').button("option", "label", "Back");
    }
};

postSave = function() {
    $('.detailadd').hide();
    $('.detailsave').show();
    $('.detailactivate').show();
    $('.detailactivate').button("option", "disabled", false);

    $('.detailcancel').button("option", "label", "Back to User");

    $('#client_txtClientName').attr("disabled", true);
    $('#client_txtClientId').attr("disabled", true);
};


SetSearchParams = function(params) {
    if (params != null) {
        advser[0].p.params = params;
        for (var i = 0; i < params.items.length; i++) {
            jQuery("#advancedsearch").addRow(params.items[i]);
        }
        if (params.items.length == 0) {
            jQuery("#advancedsearch").addRow();
        }
    } else {
        jQuery("#advancedsearch").addRow();
    }
};



//MAIN GRID

function getData(pdata) {
    var hidsearchid = $('#hidsearchid').val();
    //var hidsearchid = $('#txtSid').val();
    if (overridepage > 0) {
        pdata.page = overridepage;
    }

    if (advser[0].p.params.items.length > 0) {
        paramstring = '{seid:"' + hidsearchid + '", json:' + JSON.stringify(pdata) + ', search:' + JSON.stringify(advser[0].p.params) + '}';
    } else {
        paramstring = '{seid:"' + hidsearchid + '", json:' + JSON.stringify(pdata) + ', search:null}';
    }
    //paramstring = JSON.stringify(params);
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "/Service/Services.aspx/GetWorkspaces",
        data: paramstring,
        dataType: "json",
        success: function(data, textStatus) {
            if (textStatus == "success") {
                var thegrid = $("#list")[0];
                thegrid.addJSONData(jQuery.parseJSON(data.d));
            }
        },
        error: function(data, textStatus) {
            //alert('An error has occured retrieving data!');
        }
    });
};

FillClientRoleDDL = function(curval) {
    $('#user_role').html('');
    var urhtml = '';
    var response = FillDropdown("ClientRoleName");
    var roles = response.Column;
    $.each(roles, function(i, item) {
        urhtml += "<option value='" + item + "' "
        if (curval == item) {
            urhtml += "selected"
        }
        urhtml += " >" + item + "</option>";
    });
    $('#user_role').html(urhtml);
};

GetSelectedItem = function(key, isinternal) {
    intrnl = isinternal;
    from_outside = true;
    var hidsearchid = $('#hidsearchid').val();
    //var hidsearchid = $('#txtSid').val();
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "/Service/Services.aspx/SelectUser",
        data: '{seid:"' + hidsearchid + '", id:"' + key + '", intrnl:' + intrnl + '}',
        dataType: "json",
        success: function(data, textStatus) {
            $('#loaderwrapper').show();
            if (textStatus == "success") {
                var custrow = jQuery.parseJSON(data.d);
                if (custrow != null) {
                    ShowDetail();
                    FillUserForm(custrow);
                }
            }
            $('#loaderwrapper').hide();
        },
        error: function(data, textStatus) {
            alert('An error has occured retrieving data!');
            $('#loaderwrapper').hide();
        }
    });
};


CreateGrid = function() {
    $('#list').jqGrid({
        datatype: function(pdata) {
            $('#loaderwrapper').show();
            getData(pdata);
        },
        jsonReader: {
            root: "rows", //arry containing actual data
            page: "page", //current page
            total: "total", //total pages for the query
            records: "records", //total number of records
            repeatitems: false
            //id: "FullName" //index of the column with the PK in it
        },
        colNames: columnNames,
        colModel: columnModel,
        rowNum: 15,
        rowList: [5, 10, 15, 20, 25, 30, 35, 40, 50],
        pager: jQuery('#pager'),
        gridview: false,
        hidegrid: false,
        onPaging: function() { resizeGrid(); },
        resizeStop: function(newwidth, index) {
            //jqgrid is forcing me to jump thru alot of hoops just to allow me to resize the column and then resize the grid.
            //this is an ugly solution, but after 4 hours of cranking away at this, this is the best I can do.  
            var pg = $("#list").getGridParam('page');
            overridepage = pg;
            columnModel[index - 1].width = newwidth;
            columnModel[index - 1].widthOrg = newwidth;
            SetVCConfig();
            $("#list").jqGrid('GridUnload');
            $("#list").jqGrid('GridDestroy');
            CreateGrid();
            $("#list").trigger("reloadGrid");
            overridepage = 0;
        },
        onSelectAll: function(rowIdxArray, sts) {
        },
        onSelectRow: function(rowId) {
            $("#cb_list").removeAttr("checked")
        },
        gridComplete: function() {
            var grid = jQuery("#list");
            var ids = grid.jqGrid('getDataIDs');
            for (var i = 0; i < ids.length; i++) {
                var rowId = ids[i];
                var editbutton = "<img src='/images/edit18.png' alt='chart' title='' class='gridButton' onclick=\"EditUser(" + rowId + ");\" />";
                grid.jqGrid('setRowData', rowId, { Edit: editbutton });
                if (i % 2 !== 0) {
                    var t = $("#" + rowId, grid);
                    t.addClass('alternateRow');
                }
            }
            resizeGrid();
        },
        multiselect: true,
        rownumbers: false,
        sortname: 'Lastname',
        sortorder: 'desc',
        viewrecords: true,
        imgpath: '/CSS/themes/neopost/images',
        caption: '',
        width: '100%',
        height: '100%',
        sortable: true
    }).navGrid('#pager', { edit: false, add: false, del: false, refresh: false, view: false, search: false }, {}, {}, {}, { multipleSearch: true, overlay: false })
    $('#list').jqGrid('filterToolbar', { autosearch: true, searchOnEnter: false });

    $("#gbox_list").bind("sortstop", function(event, ui) {
        // you can even get the current permutation!
        // Yes, it looks like you may be grabbing the remapColumns function.
        //    You're not, you get an array of integers back.
        if (ui.item[0].id != 'list_Edit') {
            grid.jqGrid("getGridParam", "remapColumns");
            SetVCConfig();
        }
        var pg = $("#list").getGridParam('page');
        overridepage = pg;
        GetVCConfig();
        $("#list").jqGrid('GridUnload');
        $("#list").jqGrid('GridDestroy');
        CreateGrid();
        $("#list").trigger("reloadGrid");
        overridepage = 0;

    });

};